package com.villaday.idf.activity;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;

import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;

import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.villaday.idf.R;
import com.villaday.idf.adapter3.HomeBatchAdapter;
import com.villaday.idf.adapter3.HomeBatchTopAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.base.BaseRecyclerViewAdapter;
import com.villaday.idf.base.OnAdapterCallbackListener;
import com.villaday.idf.custom.CommonPopupWindow;
import com.villaday.idf.custom.LoadDialog;
import com.villaday.idf.custom.LoadingSaveDialog;
import com.villaday.idf.model3.BatchListEntity;
import com.villaday.idf.model3.BatchsPosterEntity;
import com.villaday.idf.model3.ConfigurationsEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.ShareUtilse;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 批量转发
 */
public class HomeBatchActivity extends BaseActivity implements OnAdapterCallbackListener {


    @BindView(R.id.toolbar_back)
    ImageButton toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_next)
    TextView toolbarNext;
    @BindView(R.id.Line_view)
    View LineView;
    @BindView(R.id.toolbar_text)
    Toolbar toolbarText;
    @BindView(R.id.rv_hb_top)
    RecyclerView rvHbTop;
    @BindView(R.id.rv_hb)
    RecyclerView rvHb;
    @BindView(R.id.srl_hb)
    SwipeRefreshLayout srlHb;
    @BindView(R.id.tv_hn_select)
    TextView tvHnSelect;
    @BindView(R.id.ll_hn_download)
    LinearLayout llHnDownload;
    @BindView(R.id.ll_hn_link)
    LinearLayout llHnLink;
    @BindView(R.id.ll_hn_photo)
    LinearLayout llHnPhoto;
    @BindView(R.id.ll_hb)
    LinearLayout llHb;
    @BindView(R.id.ll_hb_top)
    LinearLayout llHbTtop;
    @BindView(R.id.ll_hb_bottom)
    LinearLayout llHbBottom;


    private List<ConfigurationsEntity.BodyBean.MaterialTypesBean> mMaterialTypes;
    private int mPageNo = 1;
    private int mPageSize = 15;
    private LoadDialog mLoadDialog;
    private HomeBatchAdapter mHomeBatchAdapter;
    private LinearLayoutManager mLinearLayoutManager;
    private BatchListEntity mBatchListEntity;
    private CommonPopupWindow mPopurIv;


    private float mOldY = 0;
    private float mNewY = 0;
    private float mOldX = 0;
    private float mNewX = 0;
    private int mScreenNum = 6;//全屏个数
    private int mHorizontalPosition = 0;//水平位置
    private boolean mIsLoadLeft = false;//是否加载水平方向资源
    private int mVercitalPosition = 0;//垂直位置
    private boolean mIsLoadSale = false;//是否加载垂直方向资源

    private HomeBatchTopAdapter mHomeBatchTopAdapter;
    private TopSmoothScroller mScroller;
    private int mScrollY = 10;//控制手指移动距离

    private boolean isScreen = true;
    private boolean mclickScroll = false;
    private int useType = 0;//操作


    private List<List<BatchListEntity.BodyBean.ListBean>> mDataListList = new ArrayList<>();


    @Override
    protected int getViewResId() {
        return R.layout.activity_home_batch;
    }

    @Override
    protected void init() {
        super.init();
        mScroller = new TopSmoothScroller(this);
        initTopRecycle();
        //初始化列表
        initRecycle();
        //初始化界面
        initActivity();
        //得到顶部列表
        getHead();
    }


    private void initTopRecycle() {
        rvHbTop.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        mHomeBatchTopAdapter = new HomeBatchTopAdapter(this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = (int) v.getTag();
                for (int i = 0; i < mMaterialTypes.size(); i++) {
                    if (i == position) {
                        mMaterialTypes.get(i).setCheck(true);
                    } else {
                        mMaterialTypes.get(i).setCheck(false);
                    }
                }
                mHomeBatchTopAdapter.notifyDataSetChanged();
                tvHnSelect.setText("0");
                //重新请求数据
                mPageNo = 1;
                mHorizontalPosition = position;

                if (mDataListList.get(mHorizontalPosition).size() != 0) {
                    for (int i = 0; i < mDataListList.get(mHorizontalPosition).size(); i++) {
                        if (i < mScreenNum) {
                            mDataListList.get(mHorizontalPosition).get(i).setCheck(true);
                        } else {
                            mDataListList.get(mHorizontalPosition).get(i).setCheck(false);
                        }
                    }
                    tvHnSelect.setText(mScreenNum + "");
//                    LogUtil.jLog().e(mHorizontalPosition + "    " + new Gson().toJson(mDataListList.get(mHorizontalPosition)));
                    mHomeBatchAdapter.setData(mDataListList.get(mHorizontalPosition));
                    mVercitalPosition = 0;
                    scrollToPosition(mVercitalPosition);
                } else {
                    showDialog();
                    getBatchList();
                }
            }
        });
        mHomeBatchTopAdapter.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {

            }
        });
        rvHbTop.setAdapter(mHomeBatchTopAdapter);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initActivity() {
        ToolBarUtil.initToolBar(toolbarText, "批量转发", new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        srlHb.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPageNo = 1;
                getBatchList();
            }
        });


        rvHb.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (true || mLinearLayoutManager.findLastVisibleItemPosition() != 0) {
                    switch (newState) {
                        case RecyclerView.SCROLL_STATE_IDLE: //静止
                            setScrollCheck();
                            break;
                    }
                }
            }
        });
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_MOVE:
                mNewY = ev.getY();
                mNewX = ev.getX();
                if (!(Math.abs(mNewX - mOldX) < 3 && Math.abs(mNewY - mOldY) < 3)) {
                    mclickScroll = false;
                }
//                LogUtil.jLog().e("移动" + mNewX + "   " + mOldX + "  " + "     " + mNewY + "   " + mOldY + "   " + PhoneUtil.dp2px(this, 5));
                if (mLinearLayoutManager.findFirstVisibleItemPosition() == 0 && mVercitalPosition == 0 && mOldY < mNewY) {
                    return super.dispatchTouchEvent(ev);
                } else if (mDataListList != null && mDataListList.size() > 0 && mLinearLayoutManager.findLastVisibleItemPosition() == mDataListList.get(mHorizontalPosition).size() - 1 && mOldY > mNewY) {
                    return super.dispatchTouchEvent(ev);
                } else if (mOldY < PhoneUtil.dp2px(this, 120) && mNewY < PhoneUtil.dp2px(this, 120)) {
                    return super.dispatchTouchEvent(ev);
                } else {
                    return true;
                }
            case MotionEvent.ACTION_DOWN:
                mclickScroll = true;
                mOldY = ev.getY();
                mOldX = ev.getX();
                return super.dispatchTouchEvent(ev);
            case MotionEvent.ACTION_UP:
//                LogUtil.jLog().e("抬起" + mNewX + "   " + mOldX + "  " + "     " + mNewY + "   " + mOldY + "   " + PhoneUtil.dp2px(this, 5));
                if ((Math.abs(mNewX - mOldX) < mScrollY && Math.abs(mNewY - mOldY) < mScrollY) || (mNewY == 0 && mNewX == 0)) {

                } else {
                    if (Math.abs(mNewX - mOldX) > Math.abs(mNewY - mOldY)) {//判定是上下还是左右
                        if ((mOldX > mNewX && (mOldX - mNewX > mScrollY))) {//向左滑（跳右边）
                            if (mOldY < PhoneUtil.dp2px(this, 120) && mNewY < PhoneUtil.dp2px(this, 120)) {
                            } else {
                                mIsLoadLeft = true;
                                if (mHorizontalPosition < mMaterialTypes.size() - 1) {
                                    mPageNo = 1;
                                    mHorizontalPosition++;
                                    if (mDataListList.get(mHorizontalPosition).size() != 0) {
                                        mVercitalPosition = 0;
                                        scrollToPosition(mVercitalPosition);
                                        mHomeBatchAdapter.setData(mDataListList.get(mHorizontalPosition));
                                        for (int i = 0; i < mDataListList.get(mHorizontalPosition).size(); i++) {
                                            if (i < mScreenNum) {
                                                mDataListList.get(mHorizontalPosition).get(i).setCheck(true);
                                            } else {
                                                mDataListList.get(mHorizontalPosition).get(i).setCheck(false);
                                            }
                                        }
                                        tvHnSelect.setText(mScreenNum + "");
                                    } else {
                                        showDialog();
                                        getBatchList();
                                    }

                                    for (int i = 0; i < mMaterialTypes.size(); i++) {
                                        if (i == mHorizontalPosition) {
                                            mMaterialTypes.get(i).setCheck(true);
                                        } else {
                                            mMaterialTypes.get(i).setCheck(false);
                                        }
                                    }
                                    mHomeBatchTopAdapter.notifyDataSetChanged();
                                }
                            }


                        } else if (mOldX < mNewX && (mNewX - mOldX > mScrollY)) {//向右滑（往左跳）
                            if (mOldY < PhoneUtil.dp2px(this, 120) && mNewY < PhoneUtil.dp2px(this, 120)) {
                            } else {
                                if (mHorizontalPosition > 0) {
                                    mPageNo = 1;
                                    mHorizontalPosition--;
                                    if (mDataListList.get(mHorizontalPosition).size() != 0) {
                                        mVercitalPosition = 0;
                                        scrollToPosition(mVercitalPosition);
                                        mHomeBatchAdapter.setData(mDataListList.get(mHorizontalPosition));

                                        for (int i = 0; i < mDataListList.get(mHorizontalPosition).size(); i++) {
                                            if (i < mScreenNum) {
                                                mDataListList.get(mHorizontalPosition).get(i).setCheck(true);
                                            } else {
                                                mDataListList.get(mHorizontalPosition).get(i).setCheck(false);
                                            }
                                        }
                                        tvHnSelect.setText(mScreenNum + "");
                                    }
//                                getBatchList();
//                                showDialog();
//                                rvHb.setVisibility(View.GONE);

                                    for (int i = 0; i < mMaterialTypes.size(); i++) {
                                        if (i == mHorizontalPosition) {
                                            mMaterialTypes.get(i).setCheck(true);
                                        } else {
                                            mMaterialTypes.get(i).setCheck(false);
                                        }
                                    }
                                    mHomeBatchTopAdapter.notifyDataSetChanged();
                                }
                            }

                        }
                    } else {
                        if (mOldY > mNewY && mNewY != 0 && (mOldY - mNewY > mScrollY)) {//向上滑(加载)
                            if (mVercitalPosition + mScreenNum < mDataListList.get(mHorizontalPosition).size()) {
                                mVercitalPosition = mVercitalPosition + mScreenNum;
                                scrollToPosition(mVercitalPosition);
                            } else {
                                mVercitalPosition = mDataListList.get(mHorizontalPosition).size();
                                scrollToPosition(mVercitalPosition);
                            }
                        } else if (mOldY < mNewY && mNewY != 0 && (mNewY - mOldY > mScrollY)) {//向下滑动
                            if (mVercitalPosition - mScreenNum > 0) {
                                mVercitalPosition = mVercitalPosition - mScreenNum;
                                scrollToPosition(mVercitalPosition);
                            } else {
                                mVercitalPosition = 0;
                                scrollToPosition(mVercitalPosition);
                            }
                        }
                    }
//                    LogUtil.jLog().e(mVercitalPosition);
                    mNewY = 0;
                    mNewX = 0;
                }
                return super.dispatchTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    private void initRecycle() {
        mLinearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
        rvHb.setLayoutManager(mLinearLayoutManager);
        mHomeBatchAdapter = new HomeBatchAdapter(this, this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    int position = (int) v.getTag();
                    switch (v.getId()) {
                        case R.id.iv_hb_check:
                            mDataListList.get(mHorizontalPosition).get(position).setCheck(!mDataListList.get(mHorizontalPosition).get(position).isCheck());
                            mHomeBatchAdapter.notifyItemChange(position);
                            int mRvNum = 0;
                            for (int i = 0; i < mDataListList.get(mHorizontalPosition).size(); i++) {
                                if (mDataListList.get(mHorizontalPosition).get(i).isCheck()) {
                                    mRvNum++;
                                }
                            }
                            tvHnSelect.setText(mRvNum + "");
                            break;
                        case R.id.sdv_hb:
                            if (mclickScroll) {
                                BatchListEntity.BodyBean.ListBean.ProductBean product = mDataListList.get(mHorizontalPosition).get(position).getProduct();
                                setBannerSkip(product.getType(), product.getId());
                                mclickScroll = false;
                            }
                            break;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        mHomeBatchAdapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                try {

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        rvHb.setAdapter(mHomeBatchAdapter);
    }

    private void getBatchList() {
        try {
            if (mHorizontalPosition >= mMaterialTypes.size() - 1) {
                mHorizontalPosition = mMaterialTypes.size() - 1;
            }
            Map<String, String> map = new HashMap<>();
            map.put("type", mMaterialTypes.get(mHorizontalPosition).getValue() + "");
            map.put("pageNo", mPageNo + "");
            map.put("pageSize", mPageSize + "");
            LogUtil.jLog().e(mPageNo + "   " + mHorizontalPosition);
            OkHttpUtil.getJSON(this, Constant.URL.batchs, map, new OkHttpUtil.OnDataListener() {

                @Override
                public void onResponse(String url, String json) {
                    LogUtil.jLog().e(json);
                    initData(json);
                }

                @Override
                public void onFailure(String url, String error) {

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Banner跳转
     *
     * @param jumpType  跳转类型
     * @param urlString 外面的Url
     */
    private void setBannerSkip(int jumpType, String urlString) {
        switch (jumpType) {
            case 99://酒店
                Intent intentWine = new Intent(this, WineShopDetailsActivity.class);
                intentWine.putExtra("hotelId", urlString);
                startActivity(intentWine);
                break;
            case 100://房源
                Intent intent1 = new Intent(this, HouseDetailsActivityFor3.class);
                intent1.putExtra("houseId", urlString);
                intent1.putExtra("persellId", urlString);
                startActivity(intent1);
                break;
            case 101://特卖
                Intent intentTeMai = new Intent(this, HouseDetailsActivityFor3.class);
                intentTeMai.putExtra("houseId", urlString);
                intentTeMai.putExtra("persellId", urlString);
                intentTeMai.putExtra("presellProduct", true);
                startActivity(intentTeMai);
                break;
            case 97://小区
                Intent intentQu = new Intent(this, BourbonListActivity.class);
                intentQu.putExtra("villageId", urlString);
                intentQu.putExtra("city", "");
                intentQu.putExtra("area", "");
                startActivity(intentQu);
                break;
            default:
                dismissDialogAndRefresh();
        }
    }

    /**
     * 初始化数据
     *
     * @param json
     */
    private void initData(String json) {
        try {
            dismissDialogAndRefresh();
            mBatchListEntity = new Gson().fromJson(json, BatchListEntity.class);
            if (mBatchListEntity.getCode().equals(Constant.Strings.SUC)) {
//                rvHb.setVisibility(View.VISIBLE);
                if (mPageNo > 1 && mIsLoadSale && !mIsLoadLeft) {//加载
                    mIsLoadSale = false;
                    mDataListList.get(mHorizontalPosition).remove(mDataListList.get(mHorizontalPosition).size() - 1);

                    for (int i = 0; i < mBatchListEntity.getBody().getList().size(); i++) {
                        mBatchListEntity.getBody().getList().get(i).setAddType(0);
                        mDataListList.get(mHorizontalPosition).add(mBatchListEntity.getBody().getList().get(i));
                    }

                    //是否有下一页
                    if (mBatchListEntity.getBody().isHasNext()) {
                        mDataListList.get(mHorizontalPosition).add(new BatchListEntity.BodyBean.ListBean(1));
                    } else {
                        mDataListList.get(mHorizontalPosition).add(new BatchListEntity.BodyBean.ListBean(2));
                    }
                    LogUtil.jLog().e(new Gson().toJson(mDataListList));
                    mHomeBatchAdapter.notifyDataSetChanged();
                    scrollToPosition(mVercitalPosition);
                } else {
                    mVercitalPosition = 0;
                    scrollToPosition(mVercitalPosition);
                    mIsLoadLeft = false;
                    List<BatchListEntity.BodyBean.ListBean> mDataList = mBatchListEntity.getBody().getList();
                    for (int i = 0; i < mDataList.size(); i++) {
                        mDataList.get(i).setType(1);
                        mBatchListEntity.getBody().getList().get(i).setAddType(0);
                        if (i < mScreenNum) {
                            mDataList.get(i).setCheck(true);
                        } else {
                            mDataList.get(i).setCheck(false);
                        }
                    }
                    if (mBatchListEntity.getBody().isHasNext()) {
                        mDataList.add(new BatchListEntity.BodyBean.ListBean(1));
                    } else {
                        mDataList.add(new BatchListEntity.BodyBean.ListBean(2));
                    }

                    if (mDataListList.size() > mHorizontalPosition) {
                        mDataListList.set(mHorizontalPosition, mDataList);
                    } else {
                        mDataListList.add(mDataList);
                    }
                    mHomeBatchAdapter.setData(mDataListList.get(mHorizontalPosition));
                }
                tvHnSelect.setText(mScreenNum + "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getHead() {
        OkHttpUtil.getJSON(this, Constant.URL.configurations, new OkHttpUtil.OnDataListener() {
            @Override
            public void onResponse(String url, String json) {
                try {
                    LogUtil.jLog().e(json);
                    ConfigurationsEntity configurationsEntity = new Gson().fromJson(json, ConfigurationsEntity.class);
                    if (configurationsEntity.getCode().equals(Constant.Strings.SUC)) {
                        mMaterialTypes = configurationsEntity.getBody().getMaterialTypes();
                        for (int i = 0; i < mMaterialTypes.size(); i++) {
                            if (i == 0) {
                                mMaterialTypes.get(i).setCheck(true);
                            } else {
                                mMaterialTypes.get(i).setCheck(false);
                            }
                            List<BatchListEntity.BodyBean.ListBean> listBeans = new ArrayList<>();
                            mDataListList.add(listBeans);
                        }
                        mHomeBatchTopAdapter.setDatas(mMaterialTypes);

                        showDialog();
                        if ((llHbBottom.getTop() - rvHbTop.getBottom()) / PhoneUtil.dp2px(HomeBatchActivity.this, 88) > 0) {
                            int distance = llHbBottom.getTop() - rvHbTop.getTop() - PhoneUtil.dp2px(HomeBatchActivity.this, 50);
                            if (distance % PhoneUtil.dp2px(HomeBatchActivity.this, 88) > PhoneUtil.dp2px(HomeBatchActivity.this, 55)) {
                                mScreenNum = distance / PhoneUtil.dp2px(HomeBatchActivity.this, 88) + 1;
                            } else {
                                mScreenNum = distance / PhoneUtil.dp2px(HomeBatchActivity.this, 88);
                            }
                            isScreen = false;
                        }
                        getBatchList();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String url, String error) {

            }
        });
    }


    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.ll_hn_download, R.id.ll_hn_link, R.id.ll_hn_photo})
    public void btnOnclick(View view) {
        switch (view.getId()) {
            case R.id.ll_hn_download://下载海报
                useType = 0;
                userType(null);
                break;
            case R.id.ll_hn_link://转发链接
                useType = 1;
                userType(null);
                break;
            case R.id.ll_hn_photo://转发海报
                if (mDataListList.get(mHorizontalPosition) != null) {
                    mPopurIv = new CommonPopupWindow(this, R.layout.popur_wechat, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) {

                        @Override
                        protected void initView() {
                            try {
                                View view = getContentView();
                                useType = 2;
                                userType(view);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        protected void initEvent() {
                            WindowManager.LayoutParams attributes = getWindow().getAttributes();
                            attributes.alpha = 0.3f;
                            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                            getWindow().setAttributes(attributes);
                        }
                    };
                    mPopurIv.getPopupWindow().setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            WindowManager.LayoutParams attributes = getWindow().getAttributes();
                            attributes.alpha = 1.0f;
                            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                            getWindow().setAttributes(attributes);
                        }
                    });
                    mPopurIv.showAtLocation(llHbTtop, Gravity.BOTTOM, 0, 0);

                } else {
                    ToastUtil.initToast(this, "暂时不能点击");
                }
                break;
        }
    }


    public void userType(final View view) {
        try {
            showDialog();
            if (mDataListList.get(mHorizontalPosition) != null) {
                String stringBuffer = "";
                for (int j = 0; j < mDataListList.get(mHorizontalPosition).size(); j++) {
                    if (mDataListList.get(mHorizontalPosition).get(j).isCheck()) {
                        stringBuffer = stringBuffer + mDataListList.get(mHorizontalPosition).get(j).getId() + ",";
                    }
                }

                Map<String, String> map = new HashMap<>();
                map.put("materialIds", stringBuffer.length() > 0 ? stringBuffer.substring(0, stringBuffer.length() - 1) : mDataListList.get(mHorizontalPosition).get(1).getId());
                LogUtil.jLog().e(stringBuffer.substring(0, stringBuffer.length() - 1));
                OkHttpUtil.getJSON(this, Constant.URL.batchsPoster, map, new OkHttpUtil.OnDataListener() {

                    @Override
                    public void onResponse(String url, String json) {
                        LogUtil.jLog().e(json);
                        try {
                            dismissDialogAndRefresh();
                            BatchsPosterEntity batchsPosterEntity = new Gson().fromJson(json, BatchsPosterEntity.class);
                            if (batchsPosterEntity.getCode().equals(Constant.Strings.SUC) && batchsPosterEntity.getBody().size() > 0) {
                                List<BatchsPosterEntity.BodyBean> body = batchsPosterEntity.getBody();
                                StringBuffer stringBuffer = new StringBuffer();
                                List<String> picDownload = new ArrayList<>();
                                for (int j = 0; j < body.size(); j++) {
                                    if (body.get(j).getPoster() != null && body.get(j).getPoster().length() > 0) {
                                        picDownload.add(body.get(j).getPoster());
                                    }
                                    stringBuffer.append(body.get(j).getDescription() + "\n\n");
                                }
                                switch (useType) {
                                    case 0:
                                        ToastUtil.initToast(HomeBatchActivity.this, "海报已保存到相册，文案已复制");
                                        LoadingSaveDialog loadingDialog = LoadingSaveDialog.newInstance("已保存" + (1) + "/" + picDownload.size() + "张");
                                        loadingDialog.show(getFragmentManager(), "0");
                                        copy(stringBuffer.toString());
                                        saveImageForRecursive(picDownload, picDownload.size(), loadingDialog);
                                        break;
                                    case 1:
                                        ToastUtil.initToast(HomeBatchActivity.this, "文案已复制成功，快去粘贴转发");
                                        copy(stringBuffer.toString());
                                        ShareUtilse.shareTextToWeChat(HomeBatchActivity.this, " ", 0);
                                        break;
                                    case 2:
                                        final StringBuffer Buffer = stringBuffer;
                                        final List<String> picList = picDownload;

                                        view.findViewById(R.id.tv_return).setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                mPopurIv.getPopupWindow().dismiss();
                                            }
                                        });

                                        view.findViewById(R.id.ll_wechat_left).setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                showDialog();
                                                ToastUtil.initToast(HomeBatchActivity.this, "文案已复制");
                                                copy(Buffer.toString());
                                                if (picList.size() > 0) {
                                                    ShareUtilse.shareImage(HomeBatchActivity.this, 0, picList, picList.get(picList.size() - 1),"");
                                                }
                                                mPopurIv.getPopupWindow().dismiss();
                                            }
                                        });

                                        view.findViewById(R.id.ll_wechat_right).setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                showDialog();
                                               /* ToastUtil.initToast(HomeBatchActivity.this, "文案已复制，批量发多张请下载海报");
                                                copy(Buffer.toString());*/
                                                if (picList.size() > 0) {
                                                    ShareUtilse.shareImage(HomeBatchActivity.this, 1, picList, picList.get(picList.size() - 1),Buffer.toString());
                                                }
                                                mPopurIv.getPopupWindow().dismiss();
                                            }
                                        });
                                        break;

                                }

                            } else {
                                ToastUtil.initToast(HomeBatchActivity.this, batchsPosterEntity.getMsg());
                                mPopurIv.getPopupWindow().dismiss();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(String url, String error) {

                    }
                });


            } else {
                ToastUtil.initToast(this, "暂时不能点击");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void scrollToPosition(int n) {
        mScroller.setTargetPosition(n);
        mLinearLayoutManager.startSmoothScroll(mScroller);
    }


    /**
     * 复制文案
     *
     * @param copy
     */
    public void copy(String copy) {
        ClipboardManager mClipboardManager = (ClipboardManager) this.getSystemService(CLIPBOARD_SERVICE);
        ClipData mClipData = ClipData.newPlainText("test", copy);
        mClipboardManager.setPrimaryClip(mClipData);
    }

    public void setScrollCheck() {
        try {
            int firstPosition = mLinearLayoutManager.findFirstVisibleItemPosition();
            int lastPosition = mLinearLayoutManager.findLastVisibleItemPosition();

            if (lastPosition == mDataListList.get(mHorizontalPosition).size() - 1 && mIsLoadSale == false && mDataListList.get(mHorizontalPosition).get(lastPosition).getAddType() != 2) {
                mPageNo++;
                getBatchList();
                //是否加载
                mIsLoadSale = true;
            }

            if (isScreen && lastPosition != -1 && firstPosition != -1) {
                mScreenNum = lastPosition - firstPosition + 1;
                isScreen = false;
            }

            int selectNum = 0;
            for (int i = 0; i < mDataListList.get(mHorizontalPosition).size(); i++) {
                if (i >= firstPosition && i <= lastPosition) {
                    if (mDataListList.get(mHorizontalPosition).get(i).getAddType() == 1 || selectNum >= mScreenNum) {
                        mDataListList.get(mHorizontalPosition).get(i).setCheck(false);
                    } else {
                        selectNum++;
                        mDataListList.get(mHorizontalPosition).get(i).setCheck(true);
                    }
                } else {
                    mDataListList.get(mHorizontalPosition).get(i).setCheck(false);
                }
            }
            tvHnSelect.setText(selectNum + "");
            mHomeBatchAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止加载框
     */
    protected void dismissDialogAndRefresh() {
        if (mLoadDialog != null) {
            mLoadDialog.dismiss();//获取信息后关闭对话框
        }
        if (srlHb != null && srlHb.isRefreshing()) {
            srlHb.setRefreshing(false);
        }
    }

    /**
     * 设置加载框
     */
    protected void showDialog() {
        if (mLoadDialog == null) {
            mLoadDialog = LoadDialog.newInstance("加载中");
        }
        if (mLoadDialog != null && !mLoadDialog.isVisible()) {
            mLoadDialog.show(getSupportFragmentManager(), "loading");
        }

    }

    public void saveImageForRecursive(final List<String> img, final int imgSize, final LoadingSaveDialog loadingSaveDialog) {//递归保存
        if (loadingSaveDialog != null) {
            this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    loadingSaveDialog.setLoadingTips("已保存" + (imgSize - img.size() + 1) + "/" + imgSize + "张");
                }
            });

        }
        if (img.size() != 0) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    saveImageToSdCard(HomeBatchActivity.this, img.get(0), false);
                    img.remove(0);
                    saveImageForRecursive(img, imgSize, loadingSaveDialog);
                }
            }
            ).start();
        } else {

            if (loadingSaveDialog != null) {
                loadingSaveDialog.dismiss();
            }
            Looper.prepare();
            String fileName;
            if (Build.BRAND.equals("Xiaomi")) { // 小米手机
                fileName = "/DCIM/Camera/";
            } else {  // Meizu 、Oppo
                fileName = "/DCIM/Camera/";
            }
            LogUtil.jLog().e(fileName);
//            ToastUtil.initToast(this, "图文保存至" + fileName);
            ToastUtil.initToast(this, "图文保存成功！快去发朋友圈推广吧~");
            Looper.loop();
        }
    }


    public static String IMAGE_NAME = "iv_share_";
    public static int i = 0;

    //根据网络图片url路径保存到本地
    public final File saveImageToSdCard(Context context, String image, boolean isxiangce) {
        boolean success = false;
        File file = null;
        try {
            if (isxiangce) {
                file = createXiangCeImageFile(context);
            } else {
                file = createStableImageFile(context);

            }

            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);

            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));//path_export是你导出的文件路径


        } catch (Exception e) {
            e.printStackTrace();
        }

        if (success) {
            return file;
        } else {
            return null;
        }
    }

    //创建相册
    public static File createXiangCeImageFile(Context context) throws IOException {
        String imageFileName = IMAGE_NAME + System.currentTimeMillis() + ".jpg";

        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        } else {  // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        }
        file = new File(fileName);

        if (file.exists()) {
            file.delete();
        }
        return file;
    }

    //创建本地保存路径
    public static File createStableImageFile(Context context) throws IOException {

        i++;
        String imageFileName = IMAGE_NAME + System.currentTimeMillis() + ".jpg";
        File storageDir = context.getExternalCacheDir();
        File image = new File(storageDir, imageFileName);
        return image;
    }


    @Override
    public void onResume() {
        super.onResume();
        dismissDialogAndRefresh();
    }

    @Override
    public void onCallback() {
        if (mIsLoadSale == false && false) {
            mPageNo++;
            getBatchList();
            //是否加载
            mIsLoadSale = true;
        }
    }


    public class TopSmoothScroller extends LinearSmoothScroller {
        TopSmoothScroller(Context context) {
            super(context);
        }

        @Override
        protected int getHorizontalSnapPreference() {
            return SNAP_TO_START;//具体见源码注释
        }

        @Override
        protected int getVerticalSnapPreference() {
            return SNAP_TO_START;//具体见源码注释
        }
    }
}